package com.fz.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by webrx on 2017-09-06.
 */
@WebServlet("/down.action")
public class Download extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //选择要下载的文件
        //String fileName="smvc02.rar";
        //这种方式是指定下载谁就下载谁
        //String fileName="a.jpg";
        //换一种从页面传过来谁就下载谁
        String fileName=req.getParameter("name");
        //下载之后重新给他命名
        String downname=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        //要下载的文件的路径
        String path=req.getServletContext().getRealPath("/download/");
        resp.setContentType("multipart/form-data");
        //下载之后改了的新名字downname
        resp.setHeader("Content-Disposition","attachment;fileName="+downname);
        //这个流是读取要下载的文件
        InputStream is=new FileInputStream(path+"/"+fileName);
        OutputStream os=resp.getOutputStream();
        byte[] buf=new byte[10240];
    int i=0;
    while ((i=is.read(buf))>0){
        os.write(buf,0,i);
    }
    os.flush();
    os.close();
    is.close();

    }
}
